import 'package:flutter/cupertino.dart';
import 'package:flutter_base_plugin/base_library/base/base_function.dart';

class ProviderWidget<VM extends ChangeNotifier> extends StatefulWidget {
  ///加载成功后显示的页面
  final Widget? child;
  final Function(VM model) onModelReady;
  final VM viewModel;
  final ValueWidgetBuilder<VM> builder;
  final bool autoDispose;

  // ignore: use_key_in_widget_constructors
  const ProviderWidget(
      {required this.viewModel,
      required this.onModelReady,
      required this.builder,
      this.child,
      this.autoDispose = true});

  @override
  State<StatefulWidget> createState() {
    // TODO: implement createState
    return _baseViewState<VM>();
  }
}

class _baseViewState<VM extends ChangeNotifier> extends State<ProviderWidget<VM>> {
  late VM viewModel;

  @override
  void initState() {
    viewModel = widget.viewModel;
    widget.onModelReady.call(viewModel);
    // TODO: implement initState
    super.initState();
  }

  @override
  void dispose() {
    // TODO: implement dispose
    if (widget.autoDispose) viewModel.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<VM>.value(
      value: viewModel,
      child: Consumer<VM>(
        builder: widget.builder,
        // child: widget.child!,
      ),
    );
    // TODO: implement build
    // return Consumer<VM>(
    //   child: child,
    //   builder: (BuildContext context, VM viewModel, Widget? child) {
    //     if (viewModel.isSuccess()) {
    //       return child!;
    //     } else {
    //       return FutureBuilder(
    //         future: viewModel.onLoading(),
    //         builder: (context, snapshot) {
    //           if (snapshot.connectionState == ConnectionState.done) {
    //             if (viewModel.isFail()) {
    //               ///加载失败
    //               return _getErrorWidget(viewModel);
    //             } else if (viewModel.isEmpty()) {
    //               ///数据为空
    //               return _getEmptyWidget(viewModel);
    //             } else {
    //               ///加载成功
    //               return child!;
    //             }
    //           } else {
    //             ///加载中
    //             return _getLoadingWidget();
    //           }
    //         },
    //       );
    //     }
    //   },
    // );
  }


}
